import { Asset, AssetManager, assetManager } from "cc";

export class ResourceManager extends et.Entity {
    private static instance: ResourceManager;
    public static get Instance(): ResourceManager {
        return this.instance;
    }
    public static set Instance(value: ResourceManager) {
        this.instance = value;
    }
    public loadBundle(bundleUrl: string) {
        return new Promise<AssetManager.Bundle>((resolve, reject) => {
            assetManager.loadBundle(bundleUrl, (error, bundle) => {
                if (error) {
                    console.error(error);
                    reject();
                    return;
                }
                resolve(bundle);
            });
        });
    }
    public removeBundle(bundle: AssetManager.Bundle) {
        assetManager.removeBundle(bundle);
    }
    public getBundle(bundleName: string) {
        assetManager.getBundle(bundleName);
    }
    public load<T extends Asset>(bundleUrl: string, url: string) {
        return new Promise<T>((resolve, reject) => {
            assetManager.loadBundle(bundleUrl, (error, bundle) => {
                if (error) {
                    console.error(error);
                    reject();
                    return;
                }
                bundle.load(url, (error, data) => {
                    if (error) {
                        console.error(error);
                        reject();
                        return;
                    }
                    resolve(data as T);
                });
            });
        });
    }
}
@et.objectSystem(ResourceManager)
class ResourceManagerAwakeSystem extends et.AwakeSystem<ResourceManager>{
    awake(self: ResourceManager): void {
        ResourceManager.Instance = self;
    }
}